package com.imgpro.interceptor;

import com.imgpro.Constant.JwtClaimsConstant;
import com.imgpro.Context.BaseContext;
import com.imgpro.Properties.JwtProperties;
import com.imgpro.Utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.UUID;

//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;

/**
 * jwt令牌校验的拦截器
 */
@Component
@Slf4j
public class JwtTokenAdminInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

//    @Autowired
//    public StringRedisTemplate stringRedisTemplate;

    /**
     * 校验jwt
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        log.info("jwt校验拦截器preHandle开始工作了");
        //1、从请求头中获取令牌
        String token = request.getHeader(jwtProperties.getAdminTokenName());

        //2、校验令牌
        try {
//            log.info("jwt校验:{}", token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
            String userId = claims.get(JwtClaimsConstant.USER_ID).toString();
//            使用thread保存这个id
            BaseContext.setCurrentId(userId);
            log.info("当前用户uuid：{}", userId);


            //3、通过，放行
            return true;
        } catch (Exception ex) {
            //4、不通过，响应401状态码
            log.info("jwt校验失败，当前用户未登录：{}", ex.getMessage());
//          还是放行，但是当前用户未登录，不能使用存储和历史图片功能
//            response.setStatus(888);
//            TODO 未登录以后的操作，即游客用户的操作
            String uuid = UUID.randomUUID().toString();
            BaseContext.setCurrentId(uuid);
            return true;
        }
    }
//    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        BaseContext.removeCurrentId();
        log.info("当前阶段结束了，进行了threadlocal清理工作");
    }





}
